package com.qinglei.recoup.hmp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.hmp.pojo.event.SendMpAlarmInfoEvent;
import com.qinglei.recoup.hmp.pojo.event.SendMpHealthReportEvent;
import com.qinglei.recoup.hmp.pojo.event.WechatMpSubscribeEvent;
import com.qinglei.recoup.hmp.service.HmpWechatMpService;
import com.qinglei.recoup.system.domain.RadarWechat;
import com.qinglei.recoup.system.domain.UserWechat;
import com.qinglei.recoup.system.service.RadarWechatService;
import com.qinglei.recoup.system.service.UserWechatService;
import com.qinglei.recoup.system.service.WxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * <p>微信公众号测试控制器</p>
 * 测试后可以删除该控制器
 *
 * @author shiyupeng
 * @date 2022/1/8
 */
@Api(tags = "微信公众号测试控制器")
@Slf4j
@Validated
@RestController
@RequestMapping("hmp/mp-test")
public class HmpMpTestController {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private HmpWechatMpService hmpWechatMpService;
    @Autowired
    private RadarWechatService radarWechatService;

    @Autowired
    private UserWechatService userWechatService;

    @Autowired
    private WxService wxService;

    @Value("${wx.appId}")
    private  String APPID ;

    @ApiOperation(value = "微信公众号同步粉丝到平台")
    @PostMapping("/syncFan")
    public CommonRes syncFan() {
        JSONObject userList = hmpWechatMpService.getUserList();
        JSONArray openidList = userList.getJSONObject("data").getJSONArray("openid");
        for (Object openId : openidList) {
            WechatMpSubscribeEvent event = new WechatMpSubscribeEvent(applicationContext);
            event.setFromUserName(openId.toString());
            event.setEvent("subscribe");
            applicationContext.publishEvent(event);
        }
        return CommonRes.ok(openidList);
    }

    @ApiOperation(value = "发送报警消息")
    @ApiImplicitParam(name = "eventId", value = "事件ID", paramType = "query", dataType = "long", required = true)
    @PostMapping("/sendAlarm")
    public CommonRes sendAlarm(@NotNull Long eventId) {
        SendMpAlarmInfoEvent event = new SendMpAlarmInfoEvent(applicationContext);
        event.setEventId(eventId);
        applicationContext.publishEvent(event);
        return CommonRes.ok();
    }

    @ApiOperation(value = "给全部床位发送一天的健康报告消息")
    @ApiImplicitParam(name = "date", value = "日期 格式 2022-01-23", paramType = "query", dataType = "string", required = true)
    @PostMapping("/sendHealthOneDay")
    public CommonRes sendHealthReportOneDay(@NotNull String date) {
        SendMpHealthReportEvent event = new SendMpHealthReportEvent(applicationContext);
        event.setToday(LocalDate.parse(date));
        applicationContext.publishEvent(event);
        return CommonRes.ok();
    }

    @ApiOperation(value = "给指定床位发送一天的健康报告消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bedId", value = "床位ID", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "today", value = "日期 格式 2022-01-23", paramType = "query", dataType = "string", required = true)
    })
    @PostMapping("/sendHealthBed")
    public CommonRes sendHealthReport4Bed(@NotNull Integer bedId, @NotNull String today) {
        hmpWechatMpService.sendOneBedHealthReport(bedId, LocalDate.parse(today));
        return CommonRes.ok();
    }

    @ApiOperation(value = "创建自定义菜单，菜单数据在配置文件里")
    @PostMapping("/createMenu")
    public CommonRes createMenu() {
        hmpWechatMpService.createMenu();
        return CommonRes.ok();
    }

    /**
     * 给清雷科技发送消息
     * @param date
     * @return
     */
    private Executor executors = Executors.newFixedThreadPool(2);

    @ApiOperation(value = "给全部床位发送一天的健康报告消息--清雷科技")
    @ApiImplicitParam(name = "date", value = "日期 格式 2022-01-23", paramType = "query", dataType = "string", required = true)
    @PostMapping("/sendHealthOneDayKeji")
    public CommonRes sendHealthOneDayKeji() {
        log.info("sendHealthOneDayKejik开始执行===》");
        QueryWrapper queryWrapperRadarWechat = new QueryWrapper();
        queryWrapperRadarWechat.eq("is_subscribe","1") ;
        queryWrapperRadarWechat.eq("is_deleted","0");
        List<RadarWechat> userWechatList =  radarWechatService.list(queryWrapperRadarWechat);
        for(RadarWechat radarWechatTmp : userWechatList){
            QueryWrapper queryWrapperUserWechat = new QueryWrapper();
            queryWrapperUserWechat.eq("id",radarWechatTmp.getUserWechatId());
            queryWrapperUserWechat.eq("is_deleted","0");
            UserWechat userWechat  = userWechatService.getOne(queryWrapperUserWechat);
            if(userWechat!=null){
                String openId =  userWechat.getOpenId();
                String snCode =radarWechatTmp.getSnCode();
                String nickName = radarWechatTmp.getNickName();
                CompletableFuture.runAsync(() -> {
                    try {
                        sendMessage(openId,snCode,nickName);
                    } catch (Exception e) {
                        log.error("sendMessage wx error", e);
                    }
                }, executors);
            }
        }
        log.info("sendHealthOneDayKeji 发送完毕");
        return CommonRes.ok();
    }

    private void sendMessage(String openId,String snCode,String nickName){
        wxService.send_template_message(APPID,openId,snCode,nickName);
        wxService.sendTemplateMessageFirstDayOfMonth(APPID,openId,snCode,nickName);
        wxService.sendTemplateMessageFirstDayOfWeek(APPID,openId,snCode,nickName);
    }

}
